﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using Newtonsoft.Json;
using NHibernate;
using NHibernate.Criterion;
using ZLCMS.Business.Tree;
using ZLCMS.Business.Util;
using ZLCMS.Business;

namespace ZLCMS.Web.SystemManage.Basics.Doc
{
    /// <summary>
    /// 树控件数据来源，默认 CmsTreeDef 表
    /// </summary>
    public partial class TypeData : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string _userAccount;//用户

            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                ICriteria crt = session.CreateCriteria<CmsTreeDef>();
                _userAccount = UserKit.GetUserAccountFailLogin(); 
                String kind = Request["Kind"];//类型
                crt.Add(Expression.Eq("Kind", kind));
                crt.Add(Expression.Eq("OwnerAccount", _userAccount));

                if (!String.IsNullOrEmpty(Request["RootNode"]))//
                {
                    crt.Add(Expression.Gt("Parent", 0));
                }

                IList<CmsTreeDef> list = crt.AddOrder(Order.Asc("ShowOrder")).List<CmsTreeDef>();

                if (list.Count == 0 && String.IsNullOrEmpty(Request["RootNode"]))
                {
                    CmsKindInfo ki = session.Get<CmsKindInfo>(kind);

                    CmsTreeDef newNode = new CmsTreeDef();
                    newNode.Parent = 0;
                    newNode.Name = ki.KindText;
                    newNode.Kind = ki.Id;
                    newNode.Prefix = "";

                    session.Save(newNode);

                    newNode.Prefix = "_" + newNode.Id.ToString() + "_";

                    session.Flush();

                    list.Add(newNode);
                }

                List<ZTreeDataType> ztreeList = new List<ZTreeDataType>();

                foreach (CmsTreeDef item in list)
                {
                    ztreeList.Add(new ZTreeDataType() { Id = item.Id, ParentId = item.Parent, Name = item.Name  + ParamKit.GetValue("TreeDefType", item.ExtendType, "") });
                }

                Response.Write(JsonConvert.SerializeObject(ztreeList));
                Response.End();
            }
        }
    }
}
